<!--  核对完成
发货单界面中可以实现如下操作:
  // XX仓库>入库单待完成
  waitInStoreByDeliverOrder: 'waitInStoreByDeliverOrder',
  // XX仓库>入库单已完成
  completedInStoreByDeliverOrder: 'completedInStoreByDeliverOrder',
  // 采购中心>发货记录
  allDeliverOrder: 'allDeliverOrder',
-->

<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">

          <a-col :md="6" :sm="24">
            <a-form-item label="发货单号">
              <a-input v-model="queryParam.orderNumber" placeholder="请输入订单号"/>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24" v-show="$isDev">
            <!--            <a-input v-model="queryParam.orderType" placeholder="请输入订单类型"/>-->
            <a-form-item label="订单类型">
              <a-select :default-value="orderType" v-model="queryParam.orderType"
                        style="width: 120px">
                <a-select-option :value="item.id" v-for="(item, index) in orderTypeList">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24" v-show="$isDev">
            <a-form-item label="执行状态">
              <a-select :default-value="executeStatus" v-model="queryParam.executeStatus"
                        style="width: 120px">
                <a-select-option :value="id" v-for="{id, name, code} in executeStatusList">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="!advanced && 6 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
            </span>
          </a-col>

          <!-- <a-col :md="24" :sm="24">
            <a-form-item label="供应商：">
              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdSupplier">
                <a-radio-button value="">
                  全部
                </a-radio-button>
                <a-radio-button :value="id" v-for="{id, name} in $util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id, this.$businessEnum.ORG_TYPE_ENUM.NORMAL_SUPPLIER.id])">
                  {{ name }}
                </a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col> -->

          <a-col :md="24" :sm="24">
            <a-form-item label="归属公司：">
              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdCompany">
                <a-radio-button value="">
                  全部
                </a-radio-button>
                <a-radio-button :value="id" v-for="{id, name} in $util.getOrgList($businessEnum.ORG_TYPE_ENUM.COMPANY.id)">
                  {{ name }}
                </a-radio-button>
              </a-radio-group>

            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <!--   发货     -->
      <a-button v-if="viewState == $util.EMS_ORDER_VIEW_STATE.waitDeliverByPurchaseOrder"
                icon="plus" type="primary"
                @click="$refs.deliverInStoreAddForm.add({orderType, orders: selectedRows})">发货
      </a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :columns="columnsDynamic"
      :data="loadData"
      :alert="true"
      :rowKey="(record) => record.code"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >

      <span :slot="$util.EMS_ORDER_VIEW_STATE.waitInStoreByDeliverOrder" slot-scope="text, record">
        <a @click="$refs.deliverInStoreAddForm.show(record)">入库单明细</a>
      </span>

      <span :slot="$util.EMS_ORDER_VIEW_STATE.completedInStoreByDeliverOrder" slot-scope="text, record">
          <a @click="$refs.deliverInStoreDetailForm.show(record)">入库单明细</a>
      </span>

      <!--    发货单action    -->
      <span :slot="$util.EMS_ORDER_VIEW_STATE.allDeliverOrder" slot-scope="text, record">
        <a @click="$refs.deliverOrderDetailForm.show(record)">发货明细</a>
      </span>

    </s-table>

    <!--  发货单物料入库操作页  -->
    <deliver-in-store-add-form ref="deliverInStoreAddForm" @ok="handleOk"/>
    <!--  发货单物料入库操作页  -->
    <deliver-in-store-detail-form ref="deliverInStoreDetailForm" @ok="handleOk"/>
    <!--  发货单详情页  -->
    <deliver-order-detail-form ref="deliverOrderDetailForm"/>

  </a-card>
</template>

<script>
import {STable} from '@/components'
import {page, changeStatus, del, doScheduleProduction, doRecommendedProduction, doMaterialCalculation} from '@/api/modular/main/emsorder/emsOrderManage'
import {list as emsOrgList} from '@/api/modular/main/emsorg/emsOrgManage'

// 发货操作单\明细页
import deliverInStoreAddForm from '@/views/main/emsordermaterial/deliverOrder/emsInStoreAddForm'
import deliverInStoreDetailForm from '@/views/main/emsordermaterial/deliverOrder/emsInStoreDetailForm'

import deliverOrderAddForm from '@/views/main/emsordermaterial/deliverOrder/emsDeliverAddForm'
import deliverOrderDetailForm from '@/views/main/emsordermaterial/deliverOrder/emsDeliverDetailForm'


export default {
  components: {
    STable,
    deliverInStoreAddForm,
    deliverInStoreDetailForm,
    deliverOrderAddForm,
    deliverOrderDetailForm,
  },
  data() {
    return {
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      columns: [       // 表头
        {
          title: '订单号',
          dataIndex: 'orderNumber'
        },
        {
          title: '订单类型',
          dataIndex: 'orderTypeStr'
        },
        {
          title: '是否可用',
          dataIndex: 'status',
          scopedSlots: {customRender: 'status'}
        },
        {
          title: '进度状态',
          dataIndex: 'executeStatusStr'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: {customRender: 'action'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      scheduleProductionVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      urlParam: {},
      columnsType: '',
      suppliers: [],
      orgs: [],
      viewState: '',
      materialType: '',
    }
  },
  computed: {
    routePath() {
      let urlParam = this.$util.getUrlParam(this.$route.path)
      return urlParam
    },
    materialTypeUrlParam() {
      return this.routePath.materialType
    },
    materialTypeEnum() {
      return this.$util.findMaterialTypeById(this.materialType)
    },
    orderType() {
      return this.routePath.orderType
    },
    orderTypeList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
        let value = this.$businessEnum.ORDER_TYPE_ENUM[key]
        result.push(value)
      }
      return result
    },
    executeStatus() {
      return this.urlParam.executeStatus
    },
    executeStatusList() {
      let result = []
      result.push({id: '', name: '全部', code: 'all'})
      for (const key in this.$businessEnum.EXECUTE_STATUS_ENUM) {
        let value = this.$businessEnum.EXECUTE_STATUS_ENUM[key]
        result.push(value)
      }
      return result
    },
    columnsDynamic() {
      switch (this.viewState) {

        case this.$util.EMS_ORDER_VIEW_STATE.waitInStoreByDeliverOrder:
          // XX仓库>入库单待完成
          return [
            {
              title: '序号', width:'80px',
              customRender: (text, record, index) => `${index + 1}`
            },
            {
              title: '发货单号',
              dataIndex: 'orderNumber'
            },
            // {
            //   title: '总数量',
            //   dataIndex: '',
            //   customRender: (text, record, index) => `【没算】`
            // },
            // {
            //   title: '状态',
            //   dataIndex: 'status'
            // },
            {
              title: '发货时间',
              dataIndex: 'createTime'
            },
            {
              title: '操作',
              dataIndex: 'action',
              width: '250px',
              scopedSlots: {customRender: this.$util.EMS_ORDER_VIEW_STATE.waitInStoreByDeliverOrder}
            }
          ]
        case this.$util.EMS_ORDER_VIEW_STATE.completedInStoreByDeliverOrder:
          // XX仓库>入库单已完成
          return [
            {
              title: '序号', width:'80px',
              customRender: (text, record, index) => `${index + 1}`
            },
            {
              title: '发货单号',
              dataIndex: 'orderNumber'
            },
            // {
            //   title: '总数量',
            //   dataIndex: '',
            //   customRender: (text, record, index) => `【没算】`
            // },
            {
              title: '状态',
              dataIndex: 'status'
            },
            {
              title: '发货时间',
              dataIndex: 'createTime'
            },
            {
              title: '入库时间',
              dataIndex: ''
            },
            {
              title: '操作',
              dataIndex: 'action',
              width: '250px',
              scopedSlots: {customRender: this.$util.EMS_ORDER_VIEW_STATE.completedInStoreByDeliverOrder}
            }
          ]
        case this.$util.EMS_ORDER_VIEW_STATE.allDeliverOrder:
          // 采购中心>发货记录
          return [
            {
              title: '序号', width:'80px',
              customRender: (text, record, index) => `${index + 1}`
            },
            {
              title: '发货单号',
              dataIndex: 'orderNumber'
            },
            {
              title: '发货时间',
              dataIndex: 'createTime'
            },
            {
              title: '状态',
              dataIndex: 'executeStatus',
              customRender: (text, record, index) => {
                let es = this.$util.findExecuteStatusById(text)
                return es ? es.name : '未知状态'
              }
            },
            {
              title: '操作',
              width: '250px',
              scopedSlots: {customRender: this.$util.EMS_ORDER_VIEW_STATE.allDeliverOrder}
            }
          ]
        default:
          return []
      }
    }
  },
  watch: {
    '$route.path': function (newValue) {
      let urlParam = this.$util.getUrlParam(this.$route.path)
      this.urlParam = urlParam
      let {orderType, executeStatus, columnsType, viewState, materialType, refCount} = urlParam
      this.columnsType = columnsType
      this.viewState = viewState
      this.materialType = materialType
      this.queryParam = {orderType: orderType || '', executeStatus: executeStatus || ''}
      this.queryParam.materialType = materialType
      if (viewState === this.$util.EMS_ORDER_VIEW_STATE.waitDeliverByPurchaseOrder) {
        this.queryParam.refCount = 0
      } else if (viewState === this.$util.EMS_ORDER_VIEW_STATE.inProgressDeliverByPurchaseOrder) {
        this.queryParam.refCount = 0x7fffffff
      } else if (viewState === this.$util.EMS_ORDER_VIEW_STATE.completedDeliverByPurchaseOrder) {
        this.queryParam.refCount = null
      }

      setTimeout(() => {
        this.$refs.table.refresh(true)
        this.$refs.table.clearSelected()
      }, 100)
    }
  },
  created() {
    let urlParam = this.$util.getUrlParam(this.$route.path)
    this.urlParam = urlParam
    let {orderType, executeStatus, columnsType, viewState, materialType, refCount} = urlParam
    this.columnsType = columnsType
    this.viewState = viewState
    this.materialType = materialType
    this.queryParam = {orderType: orderType || '', executeStatus: executeStatus || ''}
    this.queryParam.materialType = materialType
    this.queryParam.refCount = refCount
  },
  methods: {
    del(record) {
      del(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onOrderStatusChange(checked, row) {
      row.loading = true
      let {orderId} = row
      let status = checked ? 0 : 1
      let parameter = {orderId, status}
      changeStatus(parameter).then(res => {
        this.handleOk()
      })
    },
    // 排单生产
    handleScheduleProductionShow() {
      if (this.validateScheduleProduction()) {
        this.scheduleProductionVisible = true
      }
    },
    validateScheduleProduction() {
      let selectedRows = this.selectedRows
      if (selectedRows.length == 0) {
        this.$message.error('请先选择要排单生产的订单')
        return false
      }
      let unavailableOrders = selectedRows.filter(value => value.status != 0)
      if (unavailableOrders.length > 0) {
        this.$message.error('订单状态必须为"可用"才可以进行排单')
        return false
      }
      return true
    },
    handleOkByScheduleProduction() {
      // 调接口,排单生产
      if (this.validateScheduleProduction()) {
        let orderIds = this.selectedRows.map(value => value.orderId).join(',')
        doScheduleProduction({orderIds}).then(res => {
          this.$message.success(res.message)
        })
      }
    },
    handleRecommendedProduction() {
      // 推荐生产
    },
    handleMaterialCalculation() {
      // 物料计算
      let orderIds = this.selectedRows.map(row => row.orderId).join(',')
      this.$refs.materialCalculationForm.add(orderIds)
      // doMaterialCalculation({orderIds: selectedRowKeys}).then((res) => {
      //   let data = res.data
      //
      // })
    },
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
